﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Zmotion406.Models;
using Zmotion406.Service;
using static Zmotion406.Form1;

namespace Zmotion406.Views
{
    public partial class ConfigForm : UserControl
    {
        public ConfigForm()
        {
            InitializeComponent();
            InitializeMyTimer();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void ConfigForm_Load(object sender, EventArgs e)
        {
            AxisChanged(null, null);
        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
        }
        // 获取轴配置与参数
        private AxisModel GetAxisInfo()
        {
            int StartSpeed = TypeConversion(this.StartSpeed.Text) ?? 0;
            int RunningSpeed = TypeConversion(this.RunningSpeed.Text) ?? 0;
            int AcceleratedSpeed = TypeConversion(this.AcceleratedSpeed.Text) ?? 0;
            int Deceleration = TypeConversion(this.Deceleration.Text) ?? 0;
            int Curve = TypeConversion(this.Curve.Text) ?? 0;
            int Pulse = TypeConversion(this.Pulse.Text) ?? 0;
            int PositiveLimitPosition = TypeConversion(this.PositiveLimitPosition.Text) ?? 0;
            int NegativeLimitPosition = TypeConversion(this.NegativeLimitPosition.Text) ?? 0;
            int Creep = TypeConversion(this.creep.Text) ?? 0;
            int motorPattern = GetmotorPattern() ?? 0;
            AxisModel axis = new AxisModel
            {
                StartSpeed = StartSpeed,
                RunningSpeed = RunningSpeed,
                AcceleratedSpeed = AcceleratedSpeed,
                Deceleration = Deceleration,
                Curve = Curve,
                Pulse = Pulse,
                PositiveLimitPosition = PositiveLimitPosition,
                NegativeLimitPosition = NegativeLimitPosition,
                Creep = Creep,
                motorPattern = motorPattern
            };
            return axis;

        }

        // 类型转换
        private int? TypeConversion(string text)
        {
            try
            {
                if (string.IsNullOrEmpty(text))
                {
                    return 0;
                }
                return Convert.ToInt32(text);
            }
            catch (FormatException)
            {
                MessageBox.Show("请输入整数类型参数！");
                return null;
            }
            catch (OverflowException)
            {
                MessageBox.Show("输入的数字超出了最大值！");
                return null;
            }
        }
        // 获取当前运动模式
        private int? GetmotorPattern()
        {
            if (!string.IsNullOrEmpty(this.Relative.Text))
            {
                return 1;
            }
            else if (!string.IsNullOrEmpty(this.Absolute.Text))
            {
                return 2;
            }
            return null;
        }
        /// <summary>
        /// 获取方向
        /// </summary>
        /// <returns></returns>
        private int? GetmotorDirection()
        {
            if (!string.IsNullOrEmpty(this.positive.Text))
            {
                return 1;
            }
            else if (!string.IsNullOrEmpty(this.negative.Text))
            {
                return -1;
            }
            return null;
        }


        private void SaveAxis_Click(object sender, EventArgs e)
        {
            int AxleNumber = GetAxis();
            if (AxleNumber < 0)
            {
                MessageBox.Show("请选择轴！");
                return;
            }
            AxisModel axis = GetAxisInfo();
            ConfigService.SaveAxis(AxleNumber, axis);
        }

        // 获取当前轴
        private int GetAxis()
        {
            if (this.radioX.Checked)
            {
                return 0;
            }
            else if (this.radioY.Checked)
            {
                return 1;
            }
            else if (this.radioZ.Checked)
            {
                return 2;
            }
            else if (this.radioZ.Checked)
            {
                return 3;
            }
            else
            {
                return -1;
            }
        }

        private void AllSave_Click(object sender, EventArgs e)
        {
            AxisModel axis = GetAxisInfo();
            ConfigService.SaveAllAxis(axis);
        }
        private void AxisChanged(object? sender, EventArgs? e)
        {
            if(sender != null)
            {
                int oldAxis; // 获取旧轴
                Control control = sender as Control;
                switch (control.Name.ToString())
                {
                    case "radioX":
                        oldAxis = 0;
                        break;
                    case "radioY":
                        oldAxis = 1;
                        break;
                    case "radioZ":
                        oldAxis = 2;
                        break;
                    case "radioA":
                        oldAxis = 3;
                        break;
                    default:
                        oldAxis = -1;
                        break;
                }
                AxisModel axis =  GetAxisInfo();
                ConfigModel.Allaxis[oldAxis] = axis; // 更新旧轴配置

            }
            int AxleNumber = GetAxis();
            if (ConfigModel.Allaxis.ContainsKey(AxleNumber))
            {
                AxisModel axis = ConfigModel.Allaxis[AxleNumber];

                this.StartSpeed.Text = axis.StartSpeed.ToString();
                this.RunningSpeed.Text = axis.RunningSpeed.ToString();
                this.AcceleratedSpeed.Text = axis.AcceleratedSpeed.ToString();
                this.Deceleration.Text = axis.Deceleration.ToString();
                this.Curve.Text = axis.Curve.ToString();
                this.Pulse.Text = axis.Pulse.ToString();
                this.PositiveLimitPosition.Text = axis.PositiveLimitPosition.ToString();
                this.NegativeLimitPosition.Text = axis.NegativeLimitPosition.ToString();
                this.creep.Text = axis.Creep.ToString();
                if (axis.motorPattern != 0)
                {
                    if (axis.motorPattern == 1)
                    {
                        this.Relative.Checked = true;
                    }
                    else if (axis.motorPattern == 2)
                    {
                        this.Absolute.Checked = true;
                    }
                }
                else
                {
                    this.Relative.Checked = true;
                }
            }
            else
            {
                this.StartSpeed.Text = string.Empty;
                this.RunningSpeed.Text = string.Empty;
                this.AcceleratedSpeed.Text = string.Empty;
                this.Deceleration.Text = string.Empty;
                this.Curve.Text = string.Empty;
                this.Pulse.Text = string.Empty;
                this.PositiveLimitPosition.Text = string.Empty;
                this.NegativeLimitPosition.Text = string.Empty;
                this.creep.Text = string.Empty;
                this.Relative.Checked = true;
            }
        }

        private void Btn_left_click_move_MouseDown(object sender, MouseEventArgs e)
        {
            int res = ClickMove_MouseDown(-1);
            if (res != 0)
            {
                MessageBox.Show("Btn_left_click_move_MouseDown 错误编号：" + res);
                return;
            }
        }

        private void Btn_right_click_move_MouseDown(object sender, MouseEventArgs e)
        {
            int res = ClickMove_MouseDown(1);
            if (res != 0)
            {
                MessageBox.Show("Btn_right_click_move_MouseDown 错误编号：" + res);
                return;
            }

        }

        /// <summary>
        /// 点动运动
        /// </summary>
        /// <param name="idir">正负参数</param>
        private int ClickMove_MouseDown(int idir)
        {
            int AxleNumber = GetAxis();
            AxisModel axis = GetAxisInfo();
            if (AxleNumber < 0)
            {
                MessageBox.Show("请选择轴！");
                return 9999;
            }
            int res = AxisService.RobotAxisClickMove(axis, AxleNumber, idir);
            return res;
        }

        private void Btn_left_click_move_MouseUp(object sender, MouseEventArgs e)
        {
            int AxleNumber = GetAxis();
            if (AxleNumber < 0)
            {
                MessageBox.Show("请选择轴！");
                return;
            }
            int res = AxisService.CloseMove(AxleNumber);
            if (res != 0)
            {
                MessageBox.Show("Btn_left_click_move_MouseUp 错误编号：" + res);
                return;
            }
        }

        private void Btn_right_click_move_MouseUp(object sender, MouseEventArgs e)
        {
            int AxleNumber = GetAxis();
            if (AxleNumber < 0)
            {
                MessageBox.Show("请选择轴！");
                return;
            }
            int res = AxisService.CloseMove(AxleNumber);
            if (res != 0)
            {
                MessageBox.Show("Btn_right_click_move_MouseUp 错误编号：" + res);
                return;
            }
        }

        private void Btn_left_move_Click(object sender, EventArgs e)
        {
            if (Btn_left_move.Text.ToString() == "停止运动")
            {
                int AxleNumber = GetAxis();
                if (AxleNumber < 0)
                {
                    MessageBox.Show("请选择轴！");
                    return;
                }
                AxisService.CloseMove(AxleNumber);
                Btn_left_move.Text = "左移连续";
            }
            else if (Btn_left_move.Text.ToString() == "左移连续")
            {
                int res = ClickMove_MouseDown(-1);
                if (res == 0)
                {
                    Btn_left_move.Text = "停止运动";
                }
                else
                {
                    MessageBox.Show(" Btn_left_move_Click 错误编号：" + res);
                    return;

                }
                int AxleNumber = GetAxis();
                int Alarm = AxisService.AxisAlarm(AxleNumber);  // 是否触发限位报警
                if (Alarm > 0)
                {
                    MessageBox.Show("轴报警！");
                }
            }
        }

        private void Btn_right_move_Click(object sender, EventArgs e)
        {
            if (Btn_right_move.Text.ToString() == "停止运动")
            {
                int AxleNumber = GetAxis();
                if (AxleNumber < 0)
                {
                    MessageBox.Show("请选择轴！");
                    return;
                }
                AxisService.CloseMove(AxleNumber);
                Btn_right_move.Text = "右移连续";
            }
            else if (Btn_right_move.Text.ToString() == "左移连续")
            {
                int res = ClickMove_MouseDown(1);
                if (res == 0)
                {
                    Btn_right_move.Text = "停止运动";
                }
                else
                {
                    MessageBox.Show(" Btn_right_move_Click 错误编号：" + res);
                    return;
                }
                int AxleNumber = GetAxis();
                int Alarm = AxisService.AxisAlarm(AxleNumber);  // 是否触发限位报警
                if (Alarm > 0)
                {
                    MessageBox.Show("轴报警！");
                }
            }
        }

        private void btn_sure_move_Click(object sender, EventArgs e)
        {
            int AxleNumber = GetAxis();
            int distance = TypeConversion(this.distance.Text) ?? 0;
            int direction = GetmotorDirection() ?? 0;
            if (distance == 0 || AxleNumber < 0 || direction == 0) return;
            if (btn_sure_move.Text.ToString() == "开始运动")
            {
                if (direction < 0)
                {
                    distance = -Math.Abs(distance); // 负方向
                }
                else if (direction > 0)
                {
                    distance = Math.Abs(distance); // 正方向
                }
                int res = AxisService.RobotAxisContinuousMive(GetAxisInfo(), AxleNumber, distance);
                if (res != 0)
                {
                    MessageBox.Show("btn_sure_move_Click 错误编号：" + res);
                    return;
                }
                btn_sure_move.Text = "运行中";
                btn_sure_move.BackColor = Color.Green;
                btn_sure_move.ForeColor = Color.White;
                AxisService.IsOVerMove(EndSureMove, AxleNumber); // 监听运动结束
                int Alarm = AxisService.AxisAlarm(AxleNumber);  // 是否触发限位报警
                if (Alarm > 0)
                {
                    MessageBox.Show("轴报警！");
                }
            }
        }
        private void EndSureMove(int state)
        {
            if (state == -1)
            {
                btn_sure_move.Text = "开始运动";
                btn_sure_move.BackColor = Color.LightGray;
                btn_sure_move.ForeColor = Color.Black;
            }
        }
        /// <summary>
        /// 确定归零原点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_save_origin_Click(object sender, EventArgs e)
        {
            int res = AxisService.SaveOriginMark(GetAxis());
            if (res != 0)
            {
                MessageBox.Show("归零异常！");
                return;
            }
        }
        private System.Windows.Forms.Timer CircleTimer;
        private void InitializeMyTimer()
        {
            // 创建 Timer 对象实例
            CircleTimer = new System.Windows.Forms.Timer();

            // 设置定时器间隔，单位是毫秒。以下设置为每秒触发一次
            CircleTimer.Interval = 1000;

            // 添加事件处理程序，当定时器触发时会调用此方法
            CircleTimer.Tick += new EventHandler(Inquiry_Mark);

            // 启动定时器
            CircleTimer.Start();
        }
        private void Inquiry_Mark(object? sender, EventArgs e)
        {
            int AxleNumber = GetAxis();
            if (AxleNumber != -1)
            {
                float Circle;
                int res = AxisService.Inquiry_Mark(AxleNumber, out Circle);
                if (res == 0)
                {
                    new_origin_mark.Text = Convert.ToString(Circle);
                }
            }
        }
    }
}